package basic.courseLearn14.bitOperation;

import org.junit.Test;

//使用位运算计算两数的最大值
public class FindMax {

    @Test
    public void testGetSign() {
        int num = -10;
        System.out.println(getSign(num));
        num = 10;
        System.out.println(getSign(num));
    }

    @Test
    public void testFindMax_solution1() {
        int a = 10;
        int b = 20;
        System.out.println(findMax_solution1(a, b));
        a = Integer.MIN_VALUE;
        b = 10;
        System.out.println(findMax_solution1(a, b));   //结果为2147483647，超出int范围

    }

    @Test
    public void testFindMax_solution2() {
        int a = 10;
        int b = 20;
        System.out.println(findMax_solution2(a, b));
        a = Integer.MIN_VALUE;
        b = 10;
        System.out.println(findMax_solution2(a, b));    //结果为10

    }


    //获得符号位 (1为负数，0为正数)，int位数为32位，所以最高位为符号位
    public int getSign(int num) {
        return (num >>> 31);
    }

    /**
     * 方法1：使用减法，判断符号位，问题:可能会出现越界情况
     * @param a
     * @param b
     * @return
     */
    public Integer findMax_solution1(int a, int b) {
        int result = a-b;
        int sign = getSign(result);
        if (sign == 0) {
            return a;
        }else {
            return b;
        }
    }

    /**
     * 方法2：考虑符号位，区分不同情况
     * @param a
     * @param b
     * @return
     */
    public Integer findMax_solution2(int a, int b) {
        int result = a-b;
        if (getSign(a) == getSign(b)){      //符号位相同，不会产生越界情况
            return (getSign(result) == 0)? a : b;
        }else{      //符号位不同，可能产生越界情况
            return (getSign(a) == 0)? a : b;
        }
    }







}
